﻿package com.autolinq.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jdom.JDOMException;

import com.autolinq.pojo.WeChatMessage;
import com.autolinq.service.DPCAServiceFactory;
import com.autolinq.service.DPCAWechatService;
import com.autolinq.util.Constant;
import com.autolinq.util.PushManage;
import com.autolinq.util.SHA1;

/**
 * 
 * 微信统一入口
 * 
 * @author slz
 * 
 *         2014-11-26 上午10:17:08
 */

public class WeixinServlet extends AbstractDPCAServlet {
	Logger logger = Logger.getLogger(this.getClass().getName());
	

	public WeixinServlet() {

		super();

	}

	public void destroy() {

		super.destroy();

	}
	
	@Override
    public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws javax.servlet.ServletException, java.io.IOException {
        if(null == servletRequest.getParameter("numChunks")){
            doPost(servletRequest, servletResponse);
        }else{
            doGet(servletRequest, servletResponse);
        }
    }

	/**
	 * 
	 * 微信公众平台 成为开发者验证入口
	 */

	public void doGet(HttpServletRequest request, HttpServletResponse response)

	throws ServletException, IOException {

		doPost(request, response);

	}

	/**
	 * 
	 * 微信公众平台 所有接口入口
	 */

	public void doPost(HttpServletRequest request, HttpServletResponse response)

	throws ServletException, IOException {
		logger.debug("new request come in");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String token = prop.getProperty("wechatToken");// Token
		logger.debug("current time:"+new Date());
		String rootPath = request.getRealPath("/");

		String qrcodePath = rootPath + System.getProperty("file.separator")
				+ Constant.UPLOAD_PATH + System.getProperty("file.separator");

		String signature = request.getParameter("signature");// SHA1加密字符串

		String timestamp = request.getParameter("timestamp");// 时间

		String nonce = request.getParameter("nonce");// 随机数

		String echoStr = request.getParameter("echostr");// 随机字符串
		logger.debug("TOKEN=" + token + "timestamp=" + timestamp
				+ "nonce=" + nonce + "echoStr=" + echoStr);
		if (echoStr != null) {

			String[] a = { token, timestamp, nonce };
			Arrays.sort(a);// 数组排序
			String str = "";
			for (int i = 0; i < a.length; i++) {
				str += a[i];
			}
			String echo = new SHA1().getDigestOfString(str.getBytes());// SHA1加密
			logger.debug("echo=" + echo + "signature=" + signature);
			if (echo.toLowerCase().equals(signature)) {
				logger.debug("echo=" + echo + "signature=" + signature);
				out.print(echoStr);

			} else {
				out.print("error");
			}

		} else {
			try {
				WeChatMessage message = unmarshalFromStream(request.getInputStream());
				DPCAServiceFactory factory = new DPCAServiceFactory();
				DPCAWechatService service = factory.getService(message);
				service.handleProperties(prop);
				String getXml = service.handleWechatMessage(message, qrcodePath);
				//String getXml = pushManageXml(unmarshalFromStream(request.getInputStream()), qrcodePath);
				logger.debug("send response to user:" + getXml);
				out.print(getXml);
			} catch (Exception e) {
				e.printStackTrace();
				out.print("failure");
			}
		}

		out.flush();
		out.close();
		logger.debug("response finished.");
	}
}